package com.sky.com.sky.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.sky.constant.StatusConstant;
import com.sky.dto.ReportDTO;
import com.sky.entity.Orders;
import com.sky.mapper.*;
import com.sky.result.Result;
import com.sky.service.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.List;

@Service
@RequiredArgsConstructor
public class WorkspaceServiceImpl implements WorkspaceService {
    @Autowired
    ReportMapper reportMapper;

    @Autowired
    DishMapper dishMapper;

    @Autowired
    SetmealMapper setmealMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    UserMapper userMapper;

    /**
     * 今日数据
     *
     * @return
     **/
    @Override
    public BusinessDataVO getBusinessData(LocalDate begin, LocalDate end) {
        //查询日期范围，已完成的订单
        List<ReportDTO> completeOrders = reportMapper.turnoverStatistics(begin, end, Orders.COMPLETED);
        //计算营业额
        BigDecimal turnover = new BigDecimal("0");
        for (ReportDTO completeOrder : completeOrders) {
            turnover = turnover.add(new BigDecimal(completeOrder.getTotal() + ""));
        }

        //有效订单数
        List<ReportDTO> validOrders = reportMapper.ordersStatistics(begin, end, Orders.COMPLETED);
        Integer validOrderCount = 0;
        for (ReportDTO validOrder : validOrders) {
            validOrderCount += Integer.valueOf(validOrder.getTotal() + "");
        }

        //查询日期范围，全部订单
        List<ReportDTO> allOrders = reportMapper.ordersStatistics(begin, end, null);
        Integer allOrdersCount = 0;
        for (ReportDTO allOrder : allOrders) {
            allOrdersCount += Integer.valueOf(allOrder.getTotal() + "");
        }

        //订单完成率=已完成订单 / 全部订单
        double orderCompletionRate = allOrdersCount == 0 ? 0.0 : validOrderCount * 1.0 / allOrdersCount;
        //平均客单价=营业额/有效订单数量
        BigDecimal unitPrice = validOrderCount == 0 ? new BigDecimal("0")
                : turnover.divide(new BigDecimal(validOrderCount + ""), 4, RoundingMode.HALF_UP);
        //新增用户
        List<ReportDTO> userStatistics = reportMapper.userStatistics(begin, end);
        int newUsers = 0;
        for (ReportDTO reportDTO : userStatistics) {
            newUsers += Integer.valueOf(reportDTO.getTotal().toString());
        }

        return BusinessDataVO.builder()
                .turnover(turnover.doubleValue())
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .unitPrice(unitPrice.doubleValue())
                .newUsers(newUsers)
                .build();
    }


    // 订单管理
    @Override
    public OrderOverViewVO getOverviewOrders(LocalDate currentDate) {
       // 全部订单数量
        Integer allOrders = orderMapper.countOrder(null, currentDate);
        // 已取消订单数量
        Integer cancelOders = orderMapper.countOrder(Orders.CANCELLED, currentDate);
        // 已完成数量
        Integer completeOrders = orderMapper.countOrder(Orders.COMPLETED, currentDate);
        // 待派送数量
        Integer delivereOrders = orderMapper.countOrder(Orders.CONFIRMED, currentDate);
        //待接单数量
        Integer waitingOrders = orderMapper.countOrder(Orders.TO_BE_CONFIRMED, currentDate);
        //封装并返回VO
        return OrderOverViewVO.builder()
                .allOrders(allOrders)
                .cancelledOrders(cancelOders)
                .completedOrders(completeOrders)
                .deliveredOrders(delivereOrders)
                .waitingOrders(waitingOrders)
                .build();
    }

    /**
     * 查询菜品总览
     * @return
     * **/
    @Override
    public DishOverViewVO getDishOverView() {
       // 统计起售菜品数量
        Integer sold = dishMapper.countByStatus(StatusConstant.ENABLE);
        // 统计停售菜品数量
        Integer discountinued = dishMapper.countByStatus(StatusConstant.DISABLE);
        //返回vo
        return DishOverViewVO.builder()
                .sold(sold)
                .discontinued(discountinued)
                .build();
    }

    /**
     * 查询套餐总览
     * @return 
     * **/
    @Override
    public SetmealOverViewVO getSetmealOverView() {
      //统计起售套餐数量
        Integer sold = setmealMapper.countbYStatus(StatusConstant.ENABLE);
        // 统计起售套餐是数量
        Integer discountinued = setmealMapper.countbYStatus(StatusConstant.DISABLE);
        // 返回结果
        return SetmealOverViewVO.builder()
                .sold(sold)
                .discontinued(discountinued)
                .build();
    }

    @Override
    public BusinessDataVO getBusinessData1(LocalDate begin, LocalDate end) {
        //总订单数
        Integer total = orderMapper.orderCountByDate1(null, begin, end);
        //有效订单数
        Integer validOrderCount = orderMapper.orderCountByDate1(Orders.COMPLETED, begin, end);
        //订单完成率
        Double orderCompletionRate=0.0;
        if(total != 0 && validOrderCount != 0){
            orderCompletionRate=NumberUtil.div(validOrderCount*1.0,total*1.0,2,RoundingMode.HALF_UP);
        }
        //营业额
        BigDecimal sumTurnover = orderMapper.getSumTurnover1(begin, end);
        Double turnover = sumTurnover == null ? 0.0 : sumTurnover.doubleValue();
        Double unitPrice = 0.0;//平均客单价
        if(turnover != null && validOrderCount != 0){
            unitPrice=NumberUtil.div(turnover * 1.0,validOrderCount *1.0,2,RoundingMode.HALF_UP);
        }
        //新增用户数
        Integer newUserCount = userMapper.getNewUserCount1(begin, end);

        BusinessDataVO businessDataVO = BusinessDataVO.builder()
                .total(total)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .turnover(turnover == null ? 0 : turnover)
                .unitPrice(unitPrice)
                .newUsers(newUserCount)
                .build();
        return businessDataVO;
    }

    /**
     * 查询订单管理数据
     *
     * @return
     **/
    @Override
    public OrderOverViewVO getOrderOverView() {
        LocalDate begin = LocalDate.now();
        LocalDate end = LocalDate.now();

        //待接单
        Integer waitingOrders = getNumber(begin, end, Orders.TO_BE_CONFIRMED);

        //待派送
        Integer delivereOrders = getNumber(begin, end, Orders.CONFIRMED);

        //已完成
        Integer completedOrders = getNumber(begin, end, Orders.COMPLETED);

        //已取消
        Integer cancelledOrders = getNumber(begin, end, Orders.CANCELLED);

        //全部订单
        Integer allOrders = getNumber(begin, end, null);

        return OrderOverViewVO.builder()
                .waitingOrders(waitingOrders)
                .deliveredOrders(delivereOrders)
                .completedOrders(completedOrders)
                .cancelledOrders(cancelledOrders)
                .allOrders(allOrders)
                .build();
    }

    //今日数据
    @Override
    public BusinessDataVO getBusinessData2(LocalDate currentDate) {
        //1.  查询今天营业额
        Double turnover = orderMapper.sumTurnover(Orders.COMPLETED, currentDate);
        if(turnover == null){
            turnover=0.0;
        }
        //2. 查询今天总订单
        Integer totalOrderCount = orderMapper.countOrder(null, currentDate);
        //3. 查询今天有效订单
        Integer validOrderCount = orderMapper.countOrder(Orders.COMPLETED, currentDate);
        //4. 查询今天注册用户
        Integer newUsers = userMapper.countUser(currentDate);
        //5. 计算订单完成率
        Double orderCompletionRate=0.0;
        if(validOrderCount >0 && totalOrderCount>0){
           orderCompletionRate = validOrderCount * 1.0 / totalOrderCount;

        }
        //6. 计算凭空客单价
        Double unitPrice=0.0;
        if(turnover > 0 && validOrderCount>0){
            unitPrice=turnover/validOrderCount;
        }
        // 保留2位小数
        String str22=String.format("%.2f",unitPrice);
        unitPrice=Double.parseDouble(str22);

        //7. 封装并返回VO
        return BusinessDataVO.builder()
                .newUsers(newUsers)
                .orderCompletionRate(orderCompletionRate)
                .turnover(turnover)
                .unitPrice(unitPrice)
                .validOrderCount(validOrderCount)
                .total(totalOrderCount)
                .build();
    }

    //查询对应状态的订单数量
    private Integer getNumber(LocalDate begin, LocalDate end, Integer status) {
        List<ReportDTO> reportDTOList = reportMapper.ordersStatistics(begin, end, status);
        Integer total=0;
        for (ReportDTO reportDTO : reportDTOList) {
            total+=Integer.valueOf(reportDTO.getTotal()+"");
        }
        return total;
    }
}
